Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
Getting "TypeError: Cannot read properties of undefined" when trying to access properties of an object

I have a function that grabs data from a local JSON file and renders it. Simple stuff. I do the fetch request within the useEffect hook to fire it only on the first render. Once the data is fetched, it sets it in employees. Once in employees, I use another useEffect to set some other states with data from employees.

  const [employees, setEmployees] = useState<any>([]);

  useEffect(() => {
    fetch("data.json", {
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    })
      .then(function (response) {
        return response.json();
      })
      .then(function (data) {
        setEmployees(data["employees"]);
      });
  }, []);

  useEffect(() => {
    console.log(employees)
    /* set some other state */
  }, [employees]);

/*render list of employees*/

My problem is, I can't actually access the properties within employees. When I console.log the contents of employees, this is what I see, an array of objects

[
  {
      "first_name": "John",
      "last_name": "Doe",
  },
  {
    "first_name": "Jane",
    "last_name": "Doe",
  }]

So to access the properties of the object, i've tried this


employees[0]["first_name"]

employees[0]."first_name"

employees[0][first_name]

employees[0].first_name

In the first two, I get this error


TypeError: Cannot read properties of undefined (reading 'first_name')

While in the last 2 I get this error

Cannot find name 'first_name'

If someone could tell me how to properly access my data it would be much appreciated!

Edit: I'm working in Typescript if that changes anything

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Try this one

const [employees, setEmployees] = useState<any[]>([])

link: How to declare array as any: when using UseState hook?

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda